import fs from 'node:fs'
import path from 'node:path'
import {
  type Alias,
  defineConfig,
} from 'vite'
import vue from '@vitejs/plugin-vue'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
import electron from 'vite-plugin-electron'
import pkg from './package.json'

const alias: Alias[] = [
  { find: '@', replacement: path.join(__dirname, 'src') },
  { find: 'root', replacement: __dirname },
]

export default defineConfig(env => {
  // 删除上次构建产物
  fs.rmSync(path.join(__dirname, 'dist-electron'), { recursive: true, force: true })

  return {
    plugins: [
      vue(),
      VueSetupExtend(),
      electron([
        {
          // 主进程入口文件
          entry: 'electron/main/index.ts',
          vite: {
            build: {
              minify: false,
              outDir: 'dist-electron/main',
              rollupOptions: {
                external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}),
              },
            },
            resolve: {
              alias,
            },
          },
        },
        {
          // 预加载脚本入口
          entry: 'electron/preload/index.ts',
          onstart(options) {
            // 预加载脚本重构构建后刷新渲染进程即可，而不是重启整个 Electron 应用
            options.reload()
          },
          vite: {
            build: {
              minify: false,
              outDir: 'dist-electron/preload',
            },
            resolve: {
              alias,
            },
          },
        }
      ])
    ],
    resolve: {
      alias,
    }
  }
})
